﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.Common.AssistClass
{
    public class ThreadExtension
    {
        /// <summary>
        /// 总线程数
        /// </summary>
        private int totalThreadCount;

        /// <summary>
        /// 当前执行完毕线程数
        /// </summary>
        private int currThreadCount;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="totalThreadCount">总线程数</param>
        public ThreadExtension(int totalThreadCount)
        {
            Interlocked.Exchange(ref this.totalThreadCount, totalThreadCount);
            Interlocked.Exchange(ref this.currThreadCount, 0);
        }

        /// <summary>
        /// 等待所有线程执行完毕
        /// </summary>
        /// <param name="overMiniseconds">超时时间（毫秒）</param>
        public void WaitAll(int overMiniseconds = 0)
        {
            int checkCount = 0;

            // 自旋
            while (Interlocked.CompareExchange(ref this.currThreadCount, 0, this.totalThreadCount) != this.totalThreadCount)
            {
                // 超过超时时间返回
                if (overMiniseconds > 0)
                {
                    if (checkCount >= overMiniseconds)
                    {
                        break;
                    }
                }

                checkCount++;

                Thread.Sleep(1);
            }
        }

        /// <summary>
        /// 设置信号量，表示单线程执行完毕
        /// </summary>
        public void SetOne()
        {
            Interlocked.Increment(ref this.currThreadCount);
        }
    }
}
